#include "function_select_menu.h"
#include "value_adjust_menu.h"
#include "needle_valve_menu.h"
#include "display_setting_menu.h"
#include "menu_config.h"
#include "../Application/channel_output.h"

/* 添加全屏刷新标志位 */
static bool needFullRefresh = true;
/* 显示刷新标志，决定是否需要重绘菜单界面 */
static bool sg_needRefresh = true;
/* 记录上次选中的菜单项索引，用于高亮和刷新 */
static uint8_t sg_lastSelectItem = 0;

static void OnBackEnter(const cotMenuItemInfo_t *ptItemShowInfo)
{
    /* 返回上级菜单 */
    cotMenu_Exit(true);
    cotMenu_Exit(true);
}

/* 恢复出厂设置回调函数 */
static void OnResetDefaultEnter(const cotMenuItemInfo_t *ptItemShowInfo)
{
    /* 重置所有参数为默认值并保存 */
    ResetParam();

    /* 应用显示设置 */
    LCD_SetDirection(g_tDisplayParam.direction);
    LCD_SetBacklight(g_tDisplayParam.brightness);
    set_language((SystemLanguage_e)g_tDisplayParam.language);
    
    /* 应用通道输出设置 */
    ChannelOutput_ApplyAll();
    
    /* 返回上级菜单 */
    cotMenu_Exit(true);
    cotMenu_Exit(true);
}

/* FunctionSelect菜单项定义，包含所有功能设置项 */
cotMenuList_t sg_FunctionSelectMenuTable[] =
{
    COT_MENU_ITEM_BIND(TEXT_CHANNEL1_VOLTAGE, OnValueAdjustMenuEnter, NULL, LoadValueAdjustMenu, NULL, (void*)1),
    COT_MENU_ITEM_BIND(TEXT_CHANNEL2_VOLTAGE, OnValueAdjustMenuEnter, NULL, LoadValueAdjustMenu, NULL, (void*)2),
    COT_MENU_ITEM_BIND(TEXT_CHANNEL3_VOLTAGE, OnValueAdjustMenuEnter, NULL, LoadValueAdjustMenu, NULL, (void*)3),
    COT_MENU_ITEM_BIND(TEXT_CHANNEL4_VOLTAGE, OnValueAdjustMenuEnter, NULL, LoadValueAdjustMenu, NULL, (void*)4),
    COT_MENU_ITEM_BIND(TEXT_NEEDLE_VALVE_OPENING, OnNeedleValveMenuEnter, NULL, LoadNeedleValveMenu, NULL, (void*)5),
    COT_MENU_ITEM_BIND(TEXT_CHANNEL6_CURRENT, OnValueAdjustMenuEnter, NULL, LoadValueAdjustMenu, NULL, (void*)6),
    COT_MENU_ITEM_BIND(TEXT_CHANNEL7_CURRENT, OnValueAdjustMenuEnter, NULL, LoadValueAdjustMenu, NULL, (void*)7),
    COT_MENU_ITEM_BIND(TEXT_CHANNEL8_CURRENT, OnValueAdjustMenuEnter, NULL, LoadValueAdjustMenu, NULL, (void*)8),
    COT_MENU_ITEM_BIND(TEXT_DISPLAY_SETTING, OnDisplaySettingMenuEnter, NULL, LoadDisplayMenuSetting, NULL, "Display Setting"),
    COT_MENU_ITEM_BIND(TEXT_RESET_DEFAULT, OnResetDefaultEnter, NULL, NULL, NULL, "Reset Default"),
    COT_MENU_ITEM_BIND(TEXT_BACK, OnBackEnter, NULL, NULL, NULL, "Back"),
};

/* 菜单显示函数 */
static void ShowFunctionSelectMenu(cotMenuShow_t *ptShowInfo)
{
    /* 如果不需要刷新显示，直接返回 */
    if (!sg_needRefresh)
    {
        return;
    }
    
    uint16_t i;
    uint16_t titleX;
    uint8_t showNum = MENU_MAX_SHOW_NUM; /* 每页最多显示的菜单项数（自动根据屏幕和字体大小计算） */
    uint8_t startIndex;
    static int lastStartIndex = -1;
    /* 限制显示的菜单项数量，防止越界 */
    cotMenu_LimitShowListNum(ptShowInfo, &showNum);
    /* 计算当前页起始菜单项索引 */
    startIndex = (ptShowInfo->selectItem / showNum) * showNum;
    if (startIndex != lastStartIndex)
    {
        needFullRefresh = true;
        lastStartIndex = startIndex;
    }
    if (needFullRefresh)
    {
        /* 清屏 */
        LCD_Clear();

        /* 显示菜单标题，居中显示 */
        // const char *pszSelectDesc = get_text((TextId_e)ptShowInfo->uMenuDesc.textId);
        const char *pszSelectDesc = get_text(TEXT_FUNCTION_SELECT);
        titleX = CALC_TITLE_CENTER_X(pszSelectDesc, LCD_W);
        LCD_ShowString(titleX, 0, (uint8_t *)pszSelectDesc, g_point_color, g_back_color, MENU_FONT_SIZE, 0);

        /* 在标题下方画一条横线 */
        LCD_DrawLine(0, MENU_FONT_SIZE, LCD_W - 1, MENU_FONT_SIZE, g_point_color);

        /* 首次显示时，刷新所有菜单项 */
        for (i = 0; i < showNum; i++)
        {
            uint8_t currentIndex = startIndex + i;
            if (currentIndex < COT_GET_MENU_NUM(sg_FunctionSelectMenuTable))
            {
                const char *pItemName = get_text((TextId_e)ptShowInfo->uItemsListDesc[currentIndex].textId);
                uint16_t y = CALC_MENU_ITEM_Y(i); /* 计算每项的y坐标 */
                if (currentIndex == ptShowInfo->selectItem)
                {
                    /* 选中项反色显示 */
                    LCD_ShowString(0, y, (uint8_t *)pItemName, g_back_color, g_point_color, MENU_FONT_SIZE, 0);
                }
                else
                {
                    /* 普通项正常显示 */
                    LCD_ShowString(0, y, (uint8_t *)pItemName, g_point_color, g_back_color, MENU_FONT_SIZE, 0);
                }
            }
        }
        needFullRefresh = false;
    }
    /* 只更新发生变化的菜单项，先取消旧高亮，再高亮新项 */
    if (sg_lastSelectItem != ptShowInfo->selectItem)
    {
        /* 计算上次选中项在当前页的行号 */
        uint8_t lastRow = sg_lastSelectItem - startIndex;
        if (lastRow < showNum && sg_lastSelectItem < COT_GET_MENU_NUM(sg_FunctionSelectMenuTable))
        {
            /* 取消旧高亮，恢复为普通显示 */
            const char *pItemName = get_text((TextId_e)ptShowInfo->uItemsListDesc[sg_lastSelectItem].textId);
            uint16_t y = CALC_MENU_ITEM_Y(lastRow);
            LCD_ShowString(0, y, (uint8_t *)pItemName, g_point_color, g_back_color, MENU_FONT_SIZE, 0);
        }
        /* 计算当前选中项在当前页的行号 */
        uint8_t currRow = ptShowInfo->selectItem - startIndex;
        if (currRow < showNum && ptShowInfo->selectItem < COT_GET_MENU_NUM(sg_FunctionSelectMenuTable))
        {
            /* 高亮当前选中项 */
            const char *pItemName = get_text((TextId_e)ptShowInfo->uItemsListDesc[ptShowInfo->selectItem].textId);
            uint16_t y = CALC_MENU_ITEM_Y(currRow);
            LCD_ShowString(0, y, (uint8_t *)pItemName, g_back_color, g_point_color, MENU_FONT_SIZE, 0);
        }
    }
    /* 记录本次选中项索引 */
    sg_lastSelectItem = ptShowInfo->selectItem;
    /* 清除刷新标志 */
    sg_needRefresh = false;
}

/* 按键回调函数 */
static void OnKeyFunCB(cotKey_t key)
{
    /* 处理上键短按和长按 */
    if (!cotKey_IsLongPress(KEY0))
    {
        if (cotKey_IsTriggerWayMet(KEY0, COT_KEY_TRIGGER_WAY_PRESS)) /* 按下首次触发 */
        {
            /* 预留：首次按下上键时的处理 */
        }
        if (cotKey_IsTriggerWayMet(KEY0, COT_KEY_TRIGGER_WAY_LOSSEN)) /* 识别到短按 */
        {
            cotMenu_SelectPrevious(true); /* 选中上一项 */
            sg_needRefresh = true;        /* 标记需要刷新显示 */
        }
    }
    else
    {
        if (cotKey_IsTriggerWayMet(KEY0, COT_KEY_TRIGGER_WAY_PRESS)) /* 识别到长按 */
        {
            cotMenu_SelectPrevious(true);
            sg_needRefresh = true;
        }
        if (cotKey_IsTriggerWayMet(KEY0, COT_KEY_TRIGGER_WAY_LOSSEN)) /* 长按松开 */
        {
            /* 预留：长按上键松手时的处理 */
        }
    }
    /* 处理确认键（SET）短按和长按 */
    if (!cotKey_IsLongPress(KEY2))
    {
        if (cotKey_IsTriggerWayMet(KEY2, COT_KEY_TRIGGER_WAY_LOSSEN)) /* 识别到短按 */
        {
            cotMenu_Enter(); /* 短按时进入选中的菜单项 */
        }
    }
    else
    {
        /* SET键长按3秒后触发，直接返回主菜单 */
        if (cotKey_IsTriggerWayMet(KEY2, COT_KEY_TRIGGER_WAY_PRESS)) /* 识别到长按 */
        {
            /* 逐级回到主菜单 */
            while (cotMenu_Exit(1) == 0)
            {
            }
        }
    }
    /* 处理下键短按和长按 */
    if (!cotKey_IsLongPress(KEY1))
    {
        if (cotKey_IsTriggerWayMet(KEY0, COT_KEY_TRIGGER_WAY_PRESS)) /* 按下首次触发 */
        {
            /* 预留：首次按下下键时的处理 */
        }
        if (cotKey_IsTriggerWayMet(KEY1, COT_KEY_TRIGGER_WAY_LOSSEN)) /* 识别到短按 */
        {
            cotMenu_SelectNext(true); /* 选中下一项 */
            sg_needRefresh = true;
        }
    }
    else
    {
        if (cotKey_IsTriggerWayMet(KEY1, COT_KEY_TRIGGER_WAY_PRESS)) /* 识别到长按 */
        {
            cotMenu_SelectNext(true);
            sg_needRefresh = true;
        }
        if (cotKey_IsTriggerWayMet(KEY1, COT_KEY_TRIGGER_WAY_LOSSEN)) /* 长按松开 */
        {
            /* 预留：长按下键松手时的处理 */
        }
    }
}

/* 进入回调函数 */
void OnFunctionSelectEnter(const cotMenuItemInfo_t *ptItemShowInfo)
{
    cotMenu_Bind(sg_FunctionSelectMenuTable, COT_GET_MENU_NUM(sg_FunctionSelectMenuTable), ShowFunctionSelectMenu);
}

/*
 * @brief FunctionSelect菜单加载回调函数
 *        配置按键监听和长按参数，初始化刷新标志
 * @param ptItemShowInfo 菜单项信息结构体指针
 */
void LoadFunctionSelectMenu(const cotMenuItemInfo_t *ptItemShowInfo)
{
    /* 注册按键回调 */
    cotKey_Listen(KEY0, OnKeyFunCB);
    cotKey_Listen(KEY2, OnKeyFunCB);
    cotKey_Listen(KEY1, OnKeyFunCB);

    /* 配置按键模式 */
    cotKey_ConfigLongPressMode(KEY0, 1200, 400);      /* 上键1.2秒触发长按，0.4秒重复触发 */
    cotKey_ConfigLongPressMode(KEY2, 2000, 0);       /* 设置SET键2秒触发长按，不重复触发 */
    cotKey_ConfigLongPressMode(KEY1, 1200, 400);    /* 下键1.2秒触发长按，0.4秒重复触发 */

    /* 标记需要刷新且全屏刷新 */
    sg_needRefresh = true;
    needFullRefresh = true;
}

/* 任务回调函数 */
void FunctionSelectTask(const cotMenuItemInfo_t *ptItemShowInfo)
{
    /* 预留：可在此添加菜单定时刷新、动画等功能 */
}
